/*
 * This file is part of connotea-java.
 *
 * connotea-java is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * connotea-java is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package org.connotea;

import static org.connotea.StringUtils.toBigDecimal;
import static org.connotea.StringUtils.toLong;

import java.util.ArrayList;
import java.util.List;

import org.restlet.resource.DomRepresentation;
import org.restlet.resource.Representation;
import org.restlet.util.NodeSet;
import org.w3c.dom.Node;

/**
 * Parses instances of {@link Tag} from XML representations of the same returned
 * as part of calls to the Connotea API.
 * 
 * @author <a href="mailto:christopher.townson@googlemail.com">Christopher
 *         Townson</a>
 */
public class TagParser {

    /**
     * Parse the provided {@link org.restlet.resource.Representation} as a list
     * of zero or more {@link Tag}s.
     * 
     * @param representation the {@link org.restlet.resource.Representation} of
     *            a list of zero or more {@link Tag}s to parse
     * @return the {@link Tag}s
     * @throws ParseException if the {@link org.restlet.resource.Representation}
     *             could not be parsed as a list of zero or more {@link Tag}s
     * @see #isValid(Representation)
     */
    public List<Tag> parse(Representation representation) throws ParseException {
        List<Tag> tags = new ArrayList<Tag>();
        if (!isValid(representation)) {
            throw new ParseException("invalid representation");
        }
        try {
            NodeSet nodes = new DomRepresentation(representation)
                    .getNodes("/RDF/TagList/item");
            for (Node node : nodes) {
                tags.add(getTag(node));
            }
        } catch (Exception e) {
            throw new ParseException(e);
        }
        return tags;
    }

    /**
     * Determine if the provided {@link org.restlet.resource.Representation} is
     * valid (i.e. can be parsed by this parser).
     * 
     * @param representation the {@link org.restlet.resource.Representation} to
     *            test for parseability
     * @return <code>true</code> if the
     *         {@link org.restlet.resource.Representation} is parseable as a
     *         list of zero or more {@link Tag}s
     */
    public boolean isValid(Representation representation) {
        return (representation != null)
                && (new DomRepresentation(representation)
                        .getNodes("/RDF/TagList/item") != null);
    }

    private Tag getTag(Node node) {
        Tag tag = new Tag();
        Node firstChild = node.getFirstChild();
        while (firstChild.getNextSibling() != null) {
            if ("Tag".equals(firstChild.getNodeName())) {
                Node secondChild = firstChild.getFirstChild();
                while (secondChild.getNextSibling() != null) {
                    String name = secondChild.getNodeName();
                    String text = secondChild.getTextContent();
                    if ("rdf:value".equals(name)) {
                        tag.setValue(text);
                    }
                    if ("postCount".equals(name)) {
                        tag.setPostCount(toLong(text));
                    }
                    if ("userCount".equals(name)) {
                        tag.setUserCount(toLong(text));
                    }
                    if ("usageScore".equals(name)) {
                        tag.setUsageScore(toBigDecimal(text));
                    }
                    secondChild = secondChild.getNextSibling();
                }
            }
            firstChild = firstChild.getNextSibling();
        }
        return tag;
    }
}
